
package com.guodaxia.gzh.web.user;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Joiner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.util.HashSet;
import java.util.Map;


/**
 * @author guojianquan
 * @date 2025/4/3 13:50
 */


@Controller
public class ToolsController {

    @Autowired
    public RestTemplate restTemplate;

//    Client ID:d625dd1d-fa61-4e9d-a283-8499fa7dd49e
//    Client Secret:5be8497a62842aaba673265041aa1fbaee959cdfc85053f44e194551e388441b

    public static String Secret = "5be8497a62842aaba673265041aa1fbaee959cdfc85053f44e194551e388441b";

    @RequestMapping(value = "/getTools")
    @ResponseBody
    public Map getTools(@RequestBody Map<String, Object> reqVO) {
        String realPath = (String) reqVO.get("path");
        if (StringUtils.isEmpty(realPath)) {
            realPath = "/test";
        }
        HttpMethod method = reqVO.getOrDefault("methods", "get").equals("get") ? HttpMethod.GET : HttpMethod.POST;

//        ResponseExtractor<ResponseEntity<Map>> responseEntityResponseExtractor = restTemplate.responseEntityExtractor(Map.class);
        ResponseExtractor  responseEntityResponseExtractor=null;
        RequestCallback requestCallback = new RequestCallback() {
            @Override
            public void doWithRequest(ClientHttpRequest request) throws IOException {
                HttpHeaders headers = request.getHeaders();
                headers.set("Content-Type", "application/json");

                String nonce = "gtht";
                String SignatureMethod = "HmacSHA256";
                long currentTimeMillis = System.currentTimeMillis();
                String ClientID = "d625dd1d-fa61-4e9d-a283-8499fa7dd49e";
                headers.set("Nonce", nonce);
                headers.set("SignatureMethod", SignatureMethod);
                headers.set("Timestamp", String.valueOf(currentTimeMillis));
                headers.set("ClientID", ClientID);
                String Signature = ClientID + nonce + currentTimeMillis + SignatureMethod;
                try {
                    headers.set("Signature", sha2561(Signature, Secret));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

//                reqVO.
                byte[] bytes = JSON.toJSONString(reqVO).getBytes();
                request.getBody().write(bytes);
            }

        };

        if ("get".equals(reqVO.get("methods"))) {
            realPath = realPath + "?" + Joiner.on("&")
                    // 用指定符号代替空值,key 或者value 为null都会被替换
                    .useForNull("").withKeyValueSeparator("=").join(reqVO);
            System.out.println(realPath);
        }

        ResponseEntity<Map> execute = (ResponseEntity<Map>) restTemplate.execute("https://www.idcd.com" + realPath, method, requestCallback, responseEntityResponseExtractor);
        System.out.println(JSON.toJSONString(execute));
        return execute.getBody();
    }


    public static String sha2561(String data, String key) throws Exception {
        // 获取HmacSHA256算法的Mac实例
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        // 初始化Mac实例，设置密钥
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        byte[] hash = sha256_HMAC.doFinal(data.getBytes());
        // 将哈希值转换为十六进制字符串
        String hexResult = bytesToHex(hash);
        System.out.println("Hex Result: " + hexResult);
        return hexResult;
    }

    // 辅助方法：将字节数组转换为十六进制字符串
    private static String bytesToHex(byte[] hash) {
        StringBuilder hexString = new StringBuilder(2 * hash.length);
        for (int i = 0; i < hash.length; i++) {
            String hex = Integer.toHexString(0xff & hash[i]);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }


    public int minimumOperations(int[] nums) {
        int res = 0;
        while (!isDuyiwuer(nums)) {
            res++;
            if (nums.length <= 3) {
                nums = new int[0];
            } else {
                int[] xinnums = new int[nums.length - 3];
                for (int i = 0; i < xinnums.length; i++) {
                    xinnums[i] = nums[i + 3];
                }
                nums = xinnums;
            }
        }
        return res;

    }

    boolean isDuyiwuer(int[] nums) {
        HashSet<Integer> integers = new HashSet<>();
        for (int num : nums) {
            integers.add(num);
        }
        return integers.size() == nums.length;
    }







}

